import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)

import axios from 'axios';

const store = new Vuex.Store({
    state: {
        foods: []
    },


    mutations: {
        setFoods(state, foods) {
            state.foods = foods;
        },

        setFoodNum(state, { id, n }) {

            state.foods.forEach(cate => {
                cate.content.forEach(food => {

                    if (food.id == id) {
                        food.num += n
                        // 商品数量不能小于0
                        food.num = food.num < 0 ? 0 : food.num;
                    }
                })
            })

        }


    },


    actions: {
        getFoods({ commit }) {
            let url = 'https://www.fastmock.site/mock/e136ced575da3cad433f0f5384db8e45/api/foods'

            setTimeout(() => {
                axios.get(url).then(res => {
                    commit('setFoods', res.data.data)
                })
            }, 2000)
        }
    },


    getters: {
        // 购物车数据，商品数量大于0
        cartData(state) {
            let arr = []
            state.foods.forEach(cate => {

                cate.content.forEach(food => {
                    if (food.num > 0) {
                        arr.push(food)
                    }
                })
            })

            return arr;
        }

    }
})

export default store;